import axios from "axios";
import { useRouter } from "vue-router";


// 创建axios实例
const request = axios.create({
  baseURL: "http://localhost:8080", // 后端API基础路径
  timeout: 5000,
});

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    // 添加token
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    // 处理401未授权
    if (error.response && error.response.status === 401) {
      // 清除本地存储
      localStorage.removeItem("token");
      localStorage.removeItem("userId");
      // 跳转到登录页
      const router = useRouter();
      router.push("/login");
      alert("登录已过期，请重新登录");
    }
    return Promise.reject(error);
  }
);

export default request;
